const express = require("express");
const router = express.Router();
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const moment = require("moment-timezone");
const msgUtils = require("../utils/feishu.js");
const axios = require("axios");
const poolmomo = require("../poolmomo.js");

//获取包名列表
router.post("/getFeedbackPkList", async (req, res) => {
    let user = await utils.getUserRole(req, res);
    let roleList = utils.filterFeedbackListByRoleKey(user.roleKey);
    if (user.roleAdmin || user.hasManage || user.user.name == 'zj_niuyuheng' || user.user.name == 'zj_zhangzhiwen') {
        //是管理 无条件  查询所有
        roleList = [];
    }
    let obj = req.body;
    let { page, size } = utils.pageSize(obj.page, obj.size);

    let sqlParams = [];

    let sql = `SELECT pk FROM js_app_feedback`;

    if (roleList.length > 0) {
        // 添加WHERE子句以仅返回roleList中的包名
        let pkPlaceholders = roleList.map(() => "?").join(", ");
        sql += ` WHERE pk IN (${pkPlaceholders})`;
        sqlParams.push(...roleList);
    }

    sql += ` GROUP BY pk LIMIT ?, ?`;
    sqlParams.push(page, size); // 注意，LIMIT子句中的参数调整了位置

    await pool.query(sql, sqlParams, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        const filteredResult = result.filter((item) => item.pk);
        filteredResult.forEach((item) => {
            item.package_name = item.pk;
        });
        const pksToRemove = [
            '1',
            '1222222',
            'applock.calculator.lock.hide.photo.private.vault',
            'com.seamobitech.iam',
            'com.seamobitech.tiktokdownload',
            'tik.tikdownload.nowatermark.video.downloader',
            'tiktok.tiktokdownload.nowatermark.video.downloader',
            'tt.tiktok.downloader.video.saver.nowatermark',
            'video.downloader.insta.videodownloader.ig',
            '包名',
            '包名1',
            'com.tctool.testApp',
            'com.davinci.roku',
            'com.davinci.testApp',
            'com.zhijian.LGTVRemoteTest',
            'com.ZhiJian.LGTVRemote',
            'scan.qr.code.barcode.scaner',
        ];
        const filteredData = filteredResult.filter(row => !pksToRemove.includes(row.pk));

        res.send(
            utils.returnData({
                data: utils.mapPackageNamesToShortNames(filteredData),
            })
        );
    });
});

//查询反馈列表
router.post("/getFeedbackList", async (req, res) => {
    let user = await utils.getUserRole(req, res);
    let roleList = utils.filterFeedbackListByRoleKey(user.roleKey);
    if (user.roleAdmin || user.hasManage || user.user.name == 'zj_niuyuheng' || user.user.name == 'zj_zhangzhiwen') {
        //是管理 无条件  查询所有
        roleList = [];
    }
    let { page, size } = utils.pageSize(req.body.page, req.body.size);
    let { package_name, state, dateRange } = req.body;

    const MOMO_PKS = [
        'com.trans.translationAiAndSubtitle',
        'com.TranslationAISubTitle'
    ];

    const isMomoPk = MOMO_PKS.includes(package_name);

    const dbPool = isMomoPk ? poolmomo : pool;
    const getListSumFunc = isMomoPk ? utils.getListSumMOMO : utils.getListSum;


    let sqlConditions = [];
    const sqlParams = [];
    if (package_name) {
        sqlConditions.push("pk = ?");
        sqlParams.push(package_name);
    }
    if (state) {
        sqlConditions.push("state = ?");
        sqlParams.push(state);
    }
    if (dateRange && dateRange.start && dateRange.end) {
        sqlConditions.push("first_install_time BETWEEN ? AND ?");
        sqlParams.push(dateRange.start, dateRange.end);
    }
    // roleList 条件处理
    if (roleList.length > 0) {
        // 转换roleList为一个适用于SQL IN 子句的字符串
        let roleListStr = roleList.map((item) => "?").join(", ");
        sqlConditions.push(`pk IN (${roleListStr})`);
        sqlParams.push(...roleList); // 使用扩展运算符将roleList的元素添加为参数
    }
    let sqlBase = `SELECT * FROM js_app_feedback`;
    let totalBase = "FROM js_app_feedback";
    if (sqlConditions.length > 0) {
        sqlBase += ` WHERE ${sqlConditions.join(" AND ")}`;
        totalBase += ` WHERE ${sqlConditions.join(" AND ")}`;
    }
    let sqlCount = `SELECT COUNT(*) AS total_count ${totalBase}`;

    let { total } = await getListSumFunc(sqlCount, sqlParams, res, req);

    sqlBase += " ORDER BY update_date DESC LIMIT ? OFFSET ?";
    sqlParams.push(size, page);
    await dbPool.query(sqlBase, sqlParams, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        result.forEach((element) => {
            element.package_name = element.pk;
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.first_install_time = moment(element.first_install_time)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
        });
        res.send(
            utils.returnData({
                data: utils.mapPackageNamesToShortNames(result),
                total: total,
            })
        );
    });
});
router.post("/getFeedbackListMOMO", async (req, res) => {
    let user = await utils.getUserRole(req, res);
    let roleList = utils.filterFeedbackListByRoleKey(user.roleKey);
    if (user.roleAdmin || user.hasManage) {
        //是管理 无条件  查询所有
        roleList = [];
    }
    let { page, size } = utils.pageSize(req.body.page, req.body.size);
    let { package_name, state, dateRange } = req.body;

    const MOMO_PKS = [
        'com.trans.translationAiAndSubtitle',
        'com.TranslationAISubTitle'
    ];

    const isMomoPk = MOMO_PKS.includes(package_name);

    const dbPool = isMomoPk ? poolmomo : pool;
    const getListSumFunc = isMomoPk ? utils.getListSumMOMO : utils.getListSum;


    let sqlConditions = [];
    const sqlParams = [];
    if (package_name) {
        sqlConditions.push("pk = ?");
        sqlParams.push(package_name);
    }
    if (state) {
        sqlConditions.push("state = ?");
        sqlParams.push(state);
    }
    if (dateRange && dateRange.start && dateRange.end) {
        sqlConditions.push("first_install_time BETWEEN ? AND ?");
        sqlParams.push(dateRange.start, dateRange.end);
    }
    // roleList 条件处理
    if (roleList.length > 0) {
        // 转换roleList为一个适用于SQL IN 子句的字符串
        let roleListStr = roleList.map((item) => "?").join(", ");
        sqlConditions.push(`pk IN (${roleListStr})`);
        sqlParams.push(...roleList); // 使用扩展运算符将roleList的元素添加为参数
    }
    let sqlBase = `SELECT * FROM js_app_feedback`;
    let totalBase = "FROM js_app_feedback";
    if (sqlConditions.length > 0) {
        sqlBase += ` WHERE ${sqlConditions.join(" AND ")}`;
        totalBase += ` WHERE ${sqlConditions.join(" AND ")}`;
    }
    let sqlCount = `SELECT COUNT(*) AS total_count ${totalBase}`;

    let { total } = await getListSumFunc(sqlCount, sqlParams, res, req);

    sqlBase += " ORDER BY update_date DESC LIMIT ? OFFSET ?";
    sqlParams.push(size, page);
    await dbPool.query(sqlBase, sqlParams, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        result.forEach((element) => {
            element.package_name = element.pk;
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.first_install_time = moment(element.first_install_time)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
        });
        res.send(
            utils.returnData({
                data: utils.mapPackageNamesToShortNames(result),
                total: total,
            })
        );
    });
});
//更改反馈状态
router.post("/editFeedbackState", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { id, state ,pk} = req.body;
    const MOMO_PKS = [
        'com.trans.translationAiAndSubtitle',
        'com.TranslationAISubTitle'
    ];

    const isMomoPk = MOMO_PKS.includes(pk);

    const dbPool = isMomoPk ? poolmomo : pool;
    // 更新
    let sql = `UPDATE js_app_feedback 
             SET state = ?, update_date = ?, update_by = ? 
             WHERE id = ?`;
    let values = [state, utils.formatDate(new Date()), name, id];
    await dbPool.query(sql, values, (updateErr, updateResult) => {
        if (updateErr)
            return res.send(utils.returnData({ code: -1, updateErr, req }));
        res.send({ msg: "success" });
    });
});

//反馈接口
router.post("/save", async (req, res) => {
    const {
        package_name,
        feedback_type,
        description,
        files,
        lang,
        ver,
        uuid,
        country,
        sdk,
        isp,
        first_install_time,
        operator,
        network_type,
        ip,
        videoUrl,
        tvModel,
        log_entry,
        email
    } = req.body;

    const MOMO_PKS = [
        'com.trans.translationAiAndSubtitle',
        'com.TranslationAISubTitle'
    ];

    const isMomoPk = MOMO_PKS.includes(package_name);

    const dbPool = isMomoPk ? poolmomo : pool;
    const dbQuery = isMomoPk ? utils.queryMOMO : utils.query;


    let feedback = {};
    //新增
    feedback.id = utils.createId();
    feedback.pk = package_name;
    feedback.feedback_type = feedback_type;
    feedback.description = description;
    feedback.files = files;
    feedback.lang = lang;
    feedback.tvModel = tvModel;
    feedback.email = email;
    feedback.ver = ver;
    feedback.uuid = uuid;
    feedback.country = country;
    feedback.sdk = sdk;
    feedback.isp = isp;
    feedback.first_install_time = first_install_time;
    feedback.operator = operator;
    feedback.network_type = network_type;
    feedback.ip = ip;
    feedback.videoUrl = videoUrl;
    feedback.log_entry = log_entry;
    feedback.create_by = "admin";
    feedback.update_by = "admin";
    feedback.state = 0;
    feedback.status = 0;
    feedback.create_date = utils.formatDate(new Date());
    feedback.update_date = utils.formatDate(new Date());
    const { text, values } = utils.createInsertSql("js_app_feedback", feedback);
    let result = await dbQuery(text, values);
    if (result.affectedRows == 1) {
        if (feedback.pk == 'com.seamobitech.UniversalTVRemoteControl') {
            let token = await msgUtils.getTenantAccessToken();
            let msg_type = "interactive";
            let id = `oc_00544d903e13d66a66deb2d131258c5f`;
            // let at = "";
            let content = '';
            // at = `<at id="582bb54a"></at><at id="39d85c67"></at><at id="3581b3g8"></at><at id="32b8f2b8"></at>\n\n`
            if (!log_entry) {
                content = `反馈类型:${feedback.feedback_type}\n反馈内容:${feedback.description}\n反馈时间:${moment(new Date()).tz("Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss")}`
            } else {
                content = `反馈类型:${feedback.feedback_type}\n反馈内容:${feedback.description}\n操作日志:${feedback.log_entry}\n反馈时间:${moment(new Date()).tz("Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss")}`
            }
            
            let contentMsg = {
                config: { wide_screen_mode: true, update_multi: true },
                elements: [
                    {
                        tag: "div",
                        text: {
                            content: `${content}`,
                            tag: "lark_md",
                        },
                        extra: {
                            alt: { content: "", tag: "plain_text" },
                            img_key: "img_v2_f4f6fa23-e931-4dae-8ea2-c3d398656ddg",
                            tag: "img",
                        },
                    },
                ],
                header: {
                    template: "turquoise",
                    title: {
                        content: `universalControl-用户反馈提醒`,
                        tag: "plain_text",
                    },
                },
            };
            if (files) {
                let fileUrls = files ? files.split('|') : [];
                for (let url of fileUrls) {
                    let imgKey = await uploadImage(url, token);
                    contentMsg.elements.push({
                        tag: "img",
                        img_key: imgKey,
                        alt: { content: "图片", tag: "plain_text" }
                    }); 
                }
            }
            let jsonString = JSON.stringify(contentMsg); 
            await msgUtils.sendMessage(id, msg_type, jsonString, token);
        }
        res.send({
            code: 0,
            msg: "操作成功",
        });

    } else {
        res.send(utils.returnData({ code: -1, err, req }));
    }
});
// 上传图片到飞书
async function uploadImage(url, token) {
    // 将图片 URL 转换为二进制流
    const binaryImage = await urlToBinary(url);
    const response = await axios({
        method: 'post',
        url: 'https://open.feishu.cn/open-apis/im/v1/images',
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'multipart/form-data'
        },
        data: {
            image_type: 'message',
            image: binaryImage  
        }
    });
    return response.data.data.image_key;
}
async function urlToBinary(url) {
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    return response.data;
}
module.exports = router;
